import uuid
# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from Batch_Call.models import Thread_Test
from Batch_Call.packaging import get_thread_first
from Call.packaging import seats_login, seats_logout, seats_outbound, hang_up_call, incident_push_boss, \
    pass_no_websocket, call_on_hold, bridging_call, query_seats, user_connect_call, seats_outbound1
from channels.generic.websocket import AsyncWebsocketConsumer
import json
from utils.redis_operation import redis_save, redis_delete


# 坐席登入
class Seats_login_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo', '')
        workStatus = request.data.get('workStatus', '')
        phoneType = request.data.get('phoneType', '')
        res = seats_login(agentNo=agentNo, workStatus=workStatus, phoneType=phoneType)
        return Response(res)
    def put(self, request):
        pass

    def delete(self, request):
        pass


# 坐席登出
class Seats_logout_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo', '')
        phoneType = request.data.get('phoneType', '')
        res = seats_logout(agentNo=agentNo, phoneType=phoneType)
        # 登出后删除状态
        if res.get('code','') == 200:
            redis_delete(key='%s(login)'%agentNo)
        return Response(res)
    def put(self, request):
        pass

    def delete(self, request):
        pass


# 坐席外呼
class Seats_Outbound_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo', '')
        userNumber = request.data.get('userNumber', '')
        userCli = request.data.get('userCli', '')
        agentCli = request.data.get('agentCli', '')
        userData = request.data.get('userData', '')
        ringback = request.data.get('ringback', '')
        thread_id = request.data.get('task_id','')
        dialing = request.data.get('dialing','')
        res = seats_outbound(agentNo=agentNo, userNumber=userNumber, userCli=userCli, agentCli=agentCli,
                       userData=userData, ringback=ringback,thread_id=thread_id,dialing=dialing)
        # print(res)
        return Response(res)

    def put(self, request):
        pass

    def delete(self, request):
        pass

# 坐席外呼1
class Seats_Outbound1_View(APIView):
    def get(self, request):
        return Response({"code":0000000000000000000000,"msg":"别他么发GET了！！！！！"})

    def post(self, request):
        agentNo = request.data.get('agentNo', '')
        userNumber = request.data.get('userNumber', '')
        userCli = request.data.get('userCli', '')
        agentCli = request.data.get('agentCli', '')
        userData = request.data.get('userData', '')
        ringback = request.data.get('ringback', '')
        thread_id = request.data.get('task_id','')
        dialing_type = request.data.get('dialing_type','')
        dialing_group = request.data.get('dialing_group','')
        res = seats_outbound1(agentNo=agentNo, userNumber=userNumber, userCli=userCli, agentCli=agentCli,
                       userData=userData, ringback=ringback,thread_id=thread_id,dialing_type=dialing_type,dialing_group=dialing_group)
        # print(res)
        return Response(res)

    def put(self, request):
        pass

    def delete(self, request):
        pass


# 用户接通后呼坐席
class User_Connect_Call_View(APIView):
    def post(self,request):
        userNumber = request.data.get('userNumber', '')
        userCli = request.data.get('userCli', '')
        userData = request.data.get('userData', '')
        greetPrompt = request.data.get('greetPrompt', '')
        agentNo = request.data.get('agentNo', '')
        queueId = request.data.get('queueId', '')
        callback = request.data.get('callback', '')
        res = user_connect_call(userNumber=userNumber,userCli=userCli,userData=userData,greetPrompt=greetPrompt,agentNo=agentNo,queueId=queueId,callback=callback)
        return Response(res)

# 通话保持
class Call_On_Hold_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo','')
        res = call_on_hold(agentNo=agentNo)
        return Response(res)

    def put(self, request):
        pass

    def delete(self, request):
        pass


# 桥接呼叫
class Bridging_Call_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo','')
        res = bridging_call(agentNo=agentNo)
        return Response(res)
    def put(self, request):
        pass

    def delete(self, request):
        pass


# 呼叫挂断
class Hang_Up_Call_View(APIView):
    def get(self, request):
        pass

    def post(self, request):
        agentNo = request.data.get('agentNo', '')
        return Response(hang_up_call(agentNo=agentNo))

    def put(self, request):
        pass

    def delete(self, request):
        pass

# SIP账号状态回调接口
class Sip_Status_Push_View(APIView):
    def get(self,request):
        print('GET')
        return Response({"code": 200, "msg": "成功"})
    def post(self,request):
        # 获取SIP账号
        sip_number = request.data.get('sipNumber','')
        agentNo = query_seats(sip_number)
        # SIP账号就绪后Redis存储状态
        if request.data.get('status','') == 'online':
            redis_save(key='%s(online)'%sip_number,value='SIP_%s'%sip_number)
        # SIP账号下线后Redis删除状态
        if request.data.get('status','') == 'offline':
            redis_delete(key='%s(online)'%sip_number)
        request.data['messageType'] = 'sipEvent'
        pass_no_websocket(setas=agentNo,data=request.data)
        # print(request.data)
        return Response({"code": 200, "msg": "成功"})

# 事件推送
class Incident_Push_View(APIView):
    def get(self, request):
        print('GET')
        return Response({"code": 200, "msg": "succeed"})

    def post(self, request):
        print('事件111111',request.data)
        agentNo = request.data.get('agentNo', '')
            # if request.data.get('eventName','') == 'ringing':
        #         # 添加Redis坐席忙碌状态
        #         redis_save(key='%s(busy)' % agentNo, value='agentNo_%s' % agentNo)
        #     if request.data.get('eventName','') == 'completed':
        #         # 删除redis坐席忙碌状态
        #         redis_delete(key='%s(busy)'%agentNo)
        pass_no_websocket(setas=agentNo,data=request.data)
        messageType = request.data.get('messageType', '')
        if messageType == "callEvent":
            incident_push_boss(request)
            pass
        if request.data.get('messageType','') == 'callEvent' and request.data.get('data','').get('callType','') == '2' and request.data.get('eventName','') == 'answered':
            thread_dict = request.data.get('data',{}).get('userData','')
            # 查询线索数据
            res = get_thread_first(eval(thread_dict).get('lead_id'))
            pass_no_websocket(setas=agentNo, data=res)
        return Response({"code": 200, "msg": "succeed"})

    def put(self, request):
        pass

    def delete(self, request):
        pass

# websocket
class Incident_Push_Websocket(AsyncWebsocketConsumer):
    async def connect(self):  # 连接时触发
        try:
            self.seats = self.scope['url_route']['kwargs']['seats']
        except:
            # 若无坐席号随机命名
            self.seats = uuid.uuid1()
        self.room_group_name = 'notice_%s' % self.seats  # 直接从用户指定的房间名称构造Channels组名称，不进行任何引用或转义。

        # 将新的连接加入到群组
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):  # 断开时触发
        # 将关闭的连接从群组中移除
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )
        seats_logout(agentNo=self.seats,phoneType='1')

    # Receive message from WebSocket
    async def receive(self, text_data=None, bytes_data=None):  # 接收消息时触发
        text_data_json = json.loads(text_data)
        print(text_data_json)

    # Receive message from room group
    async def system_message(self, event):
        message = event['message']
        # print('message',message)
        # Send message to WebSocket单发消息
        await self.send(text_data=json.dumps({
            'message': message
        }))